layui.use(['table', 'admin', 'ax', 'func'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;

    /**
     * 精美礼物数据管理
     */
    var NanGiftSubmission = {
        tableId: "nanGiftSubmissionTable",
        activityId: null,
        fieldConfigs: []
    };

    /**
     * 获取活动ID
     */
    NanGiftSubmission.getActivityId = function () {
        return $('#activityId').val() || 1;
    };

    /**
     * 获取字段配置
     */
    NanGiftSubmission.getFieldConfig = function (callback) {
        var ajax = new $ax(Feng.ctxPath + "/nanGiftSubmission/getFieldConfig", function (data) {
            if (data.success) {
                NanGiftSubmission.fieldConfigs = data.data;
                if (callback) {
                    callback();
                }
            } else {
                Feng.error("获取字段配置失败!");
            }
        }, function (data) {
            Feng.error("获取字段配置失败!" + data.responseJSON.message + "!");
        });
        ajax.set("activityId", NanGiftSubmission.activityId);
        ajax.start();
    };

    /**
     * 初始化表格的列（动态生成）
     */
    NanGiftSubmission.initColumn = function () {
        var columns = [
            {type: 'checkbox'},
            {align: 'center', toolbar: '#tableBar', title: '操作', width: 100},
            // {field: 'id', sort: false, title: 'ID', width: 80},
            // {field: 'userEmail', sort: false, title: '用户邮箱', width: 200},
            // {field: 'deviceCode', sort: false, title: '设备编码', width: 150}
        ];

        // 动态添加字段配置的列
        for (var i = 0; i < NanGiftSubmission.fieldConfigs.length; i++) {
            var config = NanGiftSubmission.fieldConfigs[i];
            columns.push({
                sort: false,
                title: config.fieldLabel,
                templet: (function(fieldName) {
                    return function(d) {
                        // 从formDataMap中获取对应字段的值
                        if (d.formDataMap && d.formDataMap[fieldName]) {
                            return d.formDataMap[fieldName];
                        }
                        return '-';
                    };
                })(config.fieldName)
            });
        }

        // 添加提交时间列
        columns.push({field: 'createTime', sort: true, title: '提交时间', width: 180});

        return [columns];
    };

    /**
     * 点击查询按钮
     */
    NanGiftSubmission.search = function () {
        var queryData = {
            activityId: NanGiftSubmission.activityId
        };

        table.reload(NanGiftSubmission.tableId, {
            where: queryData, page: {curr: 1}
        });
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    NanGiftSubmission.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/nanGiftSubmission/delete", function (result) {
                Feng.success("删除成功!");
                table.reload(NanGiftSubmission.tableId);
            }, function (result) {
                Feng.error("删除失败!" + result.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    /**
     * 批量删除
     */
    NanGiftSubmission.onDeleteBatch = function () {
        var checkRows = table.checkStatus(NanGiftSubmission.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要删除的数据");
            return;
        }

        var operation = function () {
            var ids = [];
            for (var i = 0; i < checkRows.data.length; i++) {
                ids.push(checkRows.data[i].id);
            }

            // 循环调用单个删除接口
            var successCount = 0;
            var errorCount = 0;
            var totalCount = ids.length;

            for (var i = 0; i < ids.length; i++) {
                var ajax = new $ax(Feng.ctxPath + "/nanGiftSubmission/delete", function (result) {
                    successCount++;
                    if (successCount + errorCount === totalCount) {
                        if (errorCount > 0) {
                            Feng.error("部分删除失败! 成功:" + successCount + " 失败:" + errorCount);
                        } else {
                            Feng.success("批量删除成功!");
                        }
                        table.reload(NanGiftSubmission.tableId);
                    }
                }, function (result) {
                    errorCount++;
                    if (successCount + errorCount === totalCount) {
                        Feng.error("部分删除失败! 成功:" + successCount + " 失败:" + errorCount);
                        table.reload(NanGiftSubmission.tableId);
                    }
                });
                ajax.set("id", ids[i]);  // 每次只传一个ID
                ajax.start();
            }
        };
        Feng.confirm("是否删除选中的 " + checkRows.data.length + " 条数据?", operation);
    };

    /**
     * 初始化表格
     */
    NanGiftSubmission.initTable = function () {
        // 渲染表格
        var tableResult = table.render({
            elem: '#' + NanGiftSubmission.tableId,
            url: Feng.ctxPath + '/nanGiftSubmission/list',
            page: true,
            limit: 20,
            height: "full-158",
            cellMinWidth: 100,
            where: {
                activityId: NanGiftSubmission.activityId
            },
            cols: NanGiftSubmission.initColumn()
        });

        // 搜索按钮点击事件
        $('#btnSearch').click(function () {
            NanGiftSubmission.search();
        });

        // 批量删除按钮点击事件
        $('#btnDelete').click(function () {
            NanGiftSubmission.onDeleteBatch();
        });

        // 排序事件
        table.on('sort(' + NanGiftSubmission.tableId + ')', function (obj) {
            table.reload(NanGiftSubmission.tableId, {
                initSort: obj,
                where: {
                    activityId: NanGiftSubmission.activityId,
                    field: obj.field.replace(/([A-Z])/g, "_$1").toLowerCase(),
                    order: obj.type
                }
            });
        });

        // 工具条点击事件
        table.on('tool(' + NanGiftSubmission.tableId + ')', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'delete') {
                NanGiftSubmission.onDeleteItem(data);
            }
        });
    };

    // 初始化
    NanGiftSubmission.activityId = NanGiftSubmission.getActivityId();
    
    // 先获取字段配置，然后初始化表格
    NanGiftSubmission.getFieldConfig(function () {
        NanGiftSubmission.initTable();
    });
});

